package com.zhaoyue.study.io.nio.socket;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 2017/1/3
 * Time: 16:21
 * To change this template use File | Settings | File Templates.
 */
public class MultipTimeServer implements Runnable {

    private Selector selector;

    private ServerSocketChannel serverSocketChannel;

    private volatile boolean stop;

    public MultipTimeServer(int port){
        try{
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);//是否阻塞
            serverSocketChannel.socket().bind(new InetSocketAddress(port),1024);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void stop(){
        this.stop = true;
    }

    @Override
    public void run() {
        try{
            while (!stop){
                selector.select(1000);//休眠时间
                Set<SelectionKey> selectionKeySet = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeySet.iterator();
                SelectionKey key = null;
                while (iterator.hasNext()){
                    key = iterator.next();
                    iterator.remove();
                    handleInput(key);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 处理请求
     * @param selectionKey
     * @throws Exception
     */
    public void handleInput(SelectionKey selectionKey) throws Exception{
        if(selectionKey.isValid()){
            if(selectionKey.isAcceptable()){
                System.out.println("服务端接收客户端连接");
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel)selectionKey.channel();
                SocketChannel socketChannel  = serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                socketChannel.register(selector,SelectionKey.OP_READ);
            }

            if(selectionKey.isReadable()){
                System.out.println("读就绪");
                SocketChannel socketChannel1 = (SocketChannel)selectionKey.channel();
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int readBytes =  socketChannel1.read(byteBuffer);
                if(readBytes > 0){
                    byteBuffer.flip();//读取数据到buff,然后反转buff,从buff读取数据
                    byte[] bytes = new byte[byteBuffer.remaining()];
                    byteBuffer.get(bytes);
                    String body = new String(bytes,"UTF-8");
                    System.out.println(body);
                    doWrite(socketChannel1,"当前时间："+System.currentTimeMillis());

                }else if(readBytes <=0){
                    selectionKey.cancel();
                    socketChannel1.close();
                }
            }
        }
    }

    /**
     *
     * @param socketChannel
     * @param resposne
     */
    public void doWrite(SocketChannel socketChannel, String resposne) throws Exception {
        if (socketChannel != null && resposne != null && resposne.trim().length() > 0) {
            byte[] bytes = resposne.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            socketChannel.write(writeBuffer);
            System.out.println("响应完毕！");
        }
    }

    public static void main(String[] args) {
        new Thread(new MultipTimeServer(8080),"Thread_server").start();
    }
}
